<template>
  <div class="mend-list container-box" style="height: calc(100% - 117px);overflow-y: auto;">
    <!-- 查询区域 -->
    <a-card class="card-header mt-25 block-box">
      <a-form-model :model="model">
        <a-row>
          <a-col :span="20">
            <a-row :gutter="24">
              <a-col :span="5" v-if="roleId != 1">
                <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="公司名称">
                  <a-select
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    v-model="model.compId"
                    :allowClear="true"
                    :filter-option="filterOption"
                    placeholder="请选择公司"
                    show-search
                    style="width: 100%"
                  >
                    <a-select-option v-for="item in companyData" :key="item.compid">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="5" v-else>
                <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="处理状态">
                  <a-select
                    :allowClear="true"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    v-model="model.resolve"
                    placeholder="请选择处理状态"
                    show-search
                    style="width: 100%;"
                  >
                    <a-select-option v-for="(item, index) in statusOption" :key="index" :value="item.value">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>

              <a-col :span="5" v-if="roleId != 1">
                <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="处理状态">
                  <a-select
                    :allowClear="true"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                    v-model="model.resolve"
                    placeholder="请选择处理状态"
                    show-search
                    style="width: 100%;"
                  >
                    <a-select-option v-for="(item, index) in statusOption" :key="index" :value="item.value">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="7">
                <a-form-model-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 5 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 19 },
                  }"
                  label="时间选择"
                >
                  <a-radio-group
                    default-value="1"
                    v-model="dateValue"
                    :disabled="disabled"
                    button-style="solid"
                    @change="onDateChange"
                  >
                    <a-radio-button value="1">
                      一个月
                    </a-radio-button>
                    <a-radio-button value="2">
                      三个月
                    </a-radio-button>
                    <a-radio-button value="3">
                      一年
                    </a-radio-button>
                    <a-radio-button value="4">
                      全部
                    </a-radio-button>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>

              <a-col :span="6">
                <a-form-model-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 9 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 15 },
                  }"
                  label="报警号/报警内容"
                >
                  <a-input v-model="model.alarmNum" placeholder="报警号/报警内容" style="width:100%" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <br v-if="collseped" />
            <a-row v-if="collseped" :gutter="24">
              <a-col :span="9">
                <a-form-model-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 3 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 19 },
                  }"
                  label="时间范围"
                >
                  <a-range-picker v-model="searchTime" style="width:100%" @change="onChange" />
                </a-form-model-item>
              </a-col>
              <a-col :span="roleId != 1 ? 10 : 7">
                <a-form-model-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 3 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 19 },
                  }"
                  label="报警级别"
                >
                  <div class="alarmStyle">
                    <ul>
                      <li
                        style="border: 1px solid #F82D2D; color: #F82D2D;background:#FFEEEE"
                        @click="clickalarmCheckType('1')"
                      >
                        <a-icon
                          v-if="alarmCheckType.indexOf('1') >= 0"
                          class="alarmIcon"
                          style="color: #F82D2D"
                          theme="filled"
                          type="check-square"
                        />
                        <a-icon
                          v-else
                          class="alarmIcon"
                          style="border:1px solid #ff3535"
                          theme="filled"
                          type="border"
                        />
                        一级报警
                      </li>
                      <li
                        style="border: 1px solid #FF7365; color: #FF7365;background:#FFF0ED"
                        @click="clickalarmCheckType('2')"
                      >
                        <a-icon
                          v-if="alarmCheckType.indexOf('2') >= 0"
                          class="alarmIcon"
                          style="color: #FF7365"
                          theme="filled"
                          type="check-square"
                        />
                        <a-icon
                          v-else
                          class="alarmIcon"
                          style="border:1px solid #FF7365"
                          theme="filled"
                          type="border"
                        />
                        二级报警
                      </li>
                      <li
                        style="border: 1px solid #FF9D62; color: #FF9D62;background:#FFF5EF"
                        @click="clickalarmCheckType('3')"
                      >
                        <a-icon
                          v-if="alarmCheckType.indexOf('3') >= 0"
                          class="alarmIcon"
                          style="color: #FF9D62"
                          theme="filled"
                          type="check-square"
                        />
                        <a-icon
                          v-else
                          class="alarmIcon"
                          style="border:1px solid #FF9D62"
                          theme="filled"
                          type="border"
                        />
                        三级报警
                      </li>
                      <li
                        style="border: 1px solid #FFB142; color: #FFB142;background:#FFF9EF"
                        @click="clickalarmCheckType('4')"
                      >
                        <a-icon
                          v-if="alarmCheckType.indexOf('4') >= 0"
                          class="alarmIcon"
                          style="color: #FFB142"
                          theme="filled"
                          type="check-square"
                        />
                        <a-icon
                          v-else
                          class="alarmIcon"
                          style="border:1px solid #FFB142"
                          theme="filled"
                          type="border"
                        />
                        系统提示信息
                        <!-- 系统提示信息 -->
                      </li>
                      <!-- <li
                        style="border: 1px solid #F82D2D; color: #F82D2D;background:#FFEEEE"
                        @click="clickalarmCheckType('5')"
                      >
                        <a-icon
                          v-if="alarmCheckType.indexOf('5') >= 0"
                          class="alarmIcon"
                          style="color: #F82D2D"
                          theme="filled"
                          type="check-square"
                        />
                        <a-icon
                          v-else
                          class="alarmIcon"
                          style="border:1px solid #ff3535"
                          theme="filled"
                          type="border"
                        />
                        非华中系统报警
                      </li> -->
                    </ul>
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="4">
            <a-row>
              <a-col style="display:flex;align-item:center">
                <div :class="{ collseped: collseped }" class="collseped-box" @click="handleCollseped">
                  <a-icon type="down" />
                  <span>{{ collsepedLabel }}</span>
                </div>
                <a-button class="btn-1" icon="search" style="margin-right: 8px;" type="primary" @click="handleSearch">
                  搜索
                </a-button>
                <a-button class="btn-2" @click="handleReset">
                  <a-icon :spin="spin" type="sync" />
                  重置
                </a-button>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <br />
    <!-- 表格区域 -->
    <a-card class="card-content mt-20">
      <a-row>
        <a-col :span="15">
          <div class="ExportBox">
            <ExportFile :fetch="getDownloadData" :fields="jsonFields" name="报警记录.xls">
              <a-button :loading="iconLoading" style="margin-right: 10px" type="primary">
                导出
              </a-button>
            </ExportFile>
            <a-button style="background:#ECAB44;color:#FFFFFF " @click="handleMoreAlarm">批量处理报警</a-button>
          </div>
        </a-col>
      </a-row>
      <div class="mt-25">
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="false"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :rowKey="(record, index) => record.id"
          :scroll="{ x: 2000 }"
        >
          <template slot="alarmNum" slot-scope="text, record">
            <div
              :style="{
                color: '#fff',
                'background-color': AlarmBack[record.alarmtype - 1],
                padding: '6px 8px',
                'font-weight': 'bold',
              }"
            >
              {{ record.alarmNum }}
            </div>
          </template>
          <!-- 状态 -->
          <template slot="resolve" slot-scope="text">
            <div class="resolveStaus">
              <div
                :style="{
                  'background-color': text === '0' ? '#FF6D6D' : '#51BB6F',
                }"
                class="circular"
              ></div>
              <div
                :style="{
                  color: text === '0' ? '#FF6D6D' : '#51BB6F',
                }"
              >
                {{ text === '0' ? '否' : '是' }}
              </div>
            </div>
          </template>
          <!-- 处理方式 -->
          <template slot="resolveMethod" slot-scope="text">
            <span style="color:#6D79FF">{{ text }}</span>
          </template>
          <!-- 状态区域-->
          <template slot="runstate" slot-scope="text">
            {{ runStateOptioncolor(text, 3) }}
          </template>
          <!-- 操作区域 -->
          <template slot="action" slot-scope="text, record">
            <a @click="handleAlarm(record)">编辑</a>
          </template>
        </a-table>
      </div>
      <div style="padding: 20px;text-align:right">
        <a-pagination
        show-quick-jumper
          v-model="model.page"
          :show-total="(total) => `共 ${total} 条记录`"
          :total="total"
          size="small"
          @change="changePage"
        />
      </div>
      <!-- 报警处理弹框 -->
      <AlarmModal ref="AlarmModal" @setData="setData" />
    </a-card>
  </div>
</template>
<script>
import api from '@/api/statisticalForm.js';
import eapi from '@/api/equipment.js';
import { AlarmBack, columns, statusOption } from './components/config';
import ExportFile from 'vue-json-excel';
import AlarmModal from './components/AlarmModal.vue';
import { computeData } from '@/unit/tool';
import moment from 'moment';
export default {
  components: { ExportFile, AlarmModal },
  data() {
    return {
      model: {
        startTime: moment()
          .subtract(1, 'months')
          .format('YYYY-MM-DD'),
        endTime: moment().format('YYYY-MM-DD'),
        alarmNum: '',
        page: 1,
        pageSize: 10,
        sortOrder: 'asc',
        alarmType: '1,2',
        username: '',
        macName: '',
        param: '',
      },
      alarmCheckType: ['1', '2'],
      spin: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      columns,
      AlarmBack, // 报警号背景色
      companyData: [], // 公司选择数据
      total: 0, // 总页数
      tableData: [], // 表格数据
      loading: false, // 表格loading
      selectedRowKeys: [], //表格选中项
      iconLoading: false, // 导出loading
      jsonFields: this.buildJsonFields(columns), // 导出表头
      replaceFields: { title: 'name', key: 'id', value: 'id', children: 'children' }, // 攻速选择配置项
      searchTime: [],
      macfacData: [], // 公司选择数据
      statusOption,
      collseped: false,
      timer: null, // 定时器
      dateValue: '1',
      disabled: false,
    };
  },
  watch: {
    searchTime(newVal) {
      if (newVal.length === 0) {
        this.disabled = false;
        this.dateValue = '4';
      }
    },
  },
  computed: {
    // 数控厂用户id
    roleId() {
      return localStorage.getItem('roleId');
    },
    // 用户信息
    userInfo() {
      return JSON.parse(localStorage.getItem('userInfo'));
    },
    collsepedLabel() {
      return this.collseped ? '收起' : '展开';
    },
  },
  created() {
    this.searchTime = [this.model.startTime, this.model.endTime];
    this.getCompanyList();
    this.getList();
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    handleSearch() {
      this.model.page = 1;
      this.getList();
    },
    // 获取表格数据
    async getList() {
      this.loading = true;
      if (this.alarmCheckType.length > 0) {
        this.model.alarmType = this.alarmCheckType.toString();
      } else {
        this.model.alarmType = '1,2';
      }
      this.$set(this.model, 'username', this.userInfo.username);
      let params = { ...this.model };
      if (!this.model.compId) {
        params = { ...this.model, compId: this.userInfo.compid };
      } else {
        params = { ...this.model };
      }
      const res = await api.SelMacAlarmByParamAndCompanyId(params);
      this.tableData = res.rows;
      this.total = res.total;
      this.loading = false;
    },
    // 收起展开
    handleCollseped() {
      this.collseped = !this.collseped;
    },
    // 处理回调
    setData() {
      this.selectedRowKeys = [];
      this.getList();
    },
    // 重置
    handleReset() {
      this.spin = true;
      this.dateValue = '1';
      this.disabled = false;
      this.model = {
        startTime: moment()
          .subtract(1, 'months')
          .format('YYYY-MM-DD'),
        endTime: moment().format('YYYY-MM-DD'),
        alarmNum: '',
        page: 1,
        pageSize: 10,
        sortOrder: 'asc',
        alarmType: '1,2',
        username: '',
        macName: '',
        param: '',
      };
      this.searchTime = [this.model.startTime, this.model.endTime];
      this.alarmCheckType = ['1', '2'];
      this.getList();
      setTimeout(() => {
        this.spin = false;
      }, 1000);
      this.$forceUpdate();
    },
    //名称下拉选择输入过滤
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    handleChange(record) {
      this.$set(this.model, 'compId', record.key);
    },
    // 选择器数据查询
    async getCompanyList() {
      this.companyData = [];
      const res = await eapi.CompanyList({ Username: this.userInfo.username });
      if (res.MsgCode !== 0) {
        this.companyData = [];
        return;
      }
      res.Data.forEach((item) => {
        this.companyData = this.companyData.concat(item.company);
      });
    },
    // 表格选中回调
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 表格分页
    changePage(page) {
      this.model.page = page;
      this.getList();
    },
    // 日期时间选择器
    onChange(date, dateString) {
      this.$set(this.model, 'startTime', dateString[0]);
      this.$set(this.model, 'endTime', dateString[1]);
      this.disabled = true;
      this.dateValue = '';
    },
    // 报警筛选回调
    clickalarmCheckType(i) {
      let index = this.alarmCheckType.indexOf(i);
      if (index >= 0) {
        let item = this.alarmCheckType.findIndex((item) => item === i);
        this.alarmCheckType.splice(item, 1);
      } else {
        this.alarmCheckType.push(i);
      }
    },
    // 导出excel 表头处理
    buildJsonFields(lists) {
      let jsonFields = {};
      lists.forEach((item) => {
        if (item.dataIndex !== 'conduct') {
          jsonFields[item.title] = item.dataIndex;
        }
      });
      return jsonFields;
    },
    // 导出
    async getDownloadData() {
      this.iconLoading = true;

      let total = this.total;
      // 单条数据
      const Single = await this.getSevenData({ page: 1, pageSize: 1 });
      // 单条数据 大小
      let SingleSize = computeData(Single);
      // 限制总大小
      let main = 20 * 1024 * 1024;
      // 可导出数量
      let num = Math.ceil(main / SingleSize);
      // 最大总页数
      let pageSize = 300;
      let MaxLength = Math.ceil(num / pageSize);
      let length = 0;
      // 判断当前后台接口返回的条数
      if (total > num) {
        length = MaxLength;
      } else {
        length = Math.ceil(total / pageSize);
      }
      let newLists = [];
      for (let i = 1; i <= length; i++) {
        let lists = await this.getSevenData({
          page: i,
          pageSize: pageSize,
        });
        newLists.push(lists);
      }
      this.iconLoading = false;

      return [].concat(...newLists);
    },
    // 获取七天前的数据
    async getSevenData(pagination) {
      if (this.alarmCheckType.length > 0) {
        this.model.alarmType = this.alarmCheckType.toString();
      } else {
        this.model.alarmType = '1,2';
      }
      let params = {};
      if (!this.model.compId) {
        params = { ...this.model, ...pagination, compId: this.userInfo.compid };
      } else {
        params = { ...this.model, ...pagination };
      }
      const res = await api.SelMacAlarmByParamAndCompanyId(params);
      this.total = res.total;
      return res.rows.map((item) => {
        if (item.resolve === '0') {
          item.resolve = '否';
        } else {
          item.resolve = '是';
        }
        item.macnumb = item.macnumb.toString();
        return item;
      });
    },
    handleAlarm(record) {
      this.$refs.AlarmModal.showModal();
      this.$refs.AlarmModal.model.ids = record.id.toString();
    },
    // 批量处理报警
    handleMoreAlarm() {
      if (this.selectedRowKeys.length > 0) {
        this.$refs.AlarmModal.showModal();
        this.$refs.AlarmModal.model.ids = this.selectedRowKeys.toString();
      } else {
        this.$message.error('请选择需要处理的报警记录');
      }
    },
    onDateChange(e) {
      this.dateValue = e.target.value;
      this.$set(this.model, 'endTime', moment().format('YYYY-MM-DD'));
      switch (e.target.value) {
        case '1':
          this.$set(
            this.model,
            'startTime',
            moment()
              .subtract(1, 'months')
              .format('YYYY-MM-DD')
          );
          break;
        case '2':
          this.$set(
            this.model,
            'startTime',
            moment()
              .subtract(3, 'months')
              .format('YYYY-MM-DD')
          );
          break;
        case '3':
          this.$set(
            this.model,
            'startTime',
            moment()
              .subtract(1, 'years')
              .format('YYYY-MM-DD')
          );
          break;
        case '4':
          this.$set(this.model, 'startTime', '');
          this.$set(this.model, 'endTime', '');
          break;
      }
      this.searchTime = [this.model.startTime, this.model.endTime];
      this.$forceUpdate();
    },
  },
};
</script>
<style lang="less" scoped>
@import url('./index.less');
</style>
